// 在顶部添加 canvas 的导入
import { Game, canvas } from './game-state.js';
import { shootBullet } from './game.js';

// 添加图像加载函数
function loadImage(src) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = () => reject(new Error(`Failed to load image at ${src}`));
        img.src = src;
    });
}

// 在 Game 初始化时加载图像
loadImage('./js/tank.jpg')
    .then(img => {
        Game.player.image = img;
    })
    .catch(error => {
        console.error(error);
    });

// 添加得分变量
Game.player.score = 0;

// 添加原来的图片路径变量
let originalImageSrc = './js/tank.jpg';

// 添加图片替换函数
function replacePlayerImage(src) {
    loadImage(src)
        .then(img => {
            Game.player.image = img;
        })
        .catch(error => {
            console.error(error);
        });
}

export function controlPlayer() {
    // 现有的玩家控制逻辑
    if (Game.keys['ArrowUp']) {
        Game.player.y -= Game.player.speed;
        Game.player.direction = 0;
    }
    if (Game.keys['ArrowDown']) {
        Game.player.y += Game.player.speed;
        Game.player.direction = 2;
    }
    if (Game.keys['ArrowLeft']) {
        Game.player.x -= Game.player.speed;
        Game.player.direction = 3;
    }
    if (Game.keys['ArrowRight']) {
        Game.player.x += Game.player.speed;
        Game.player.direction = 1;
    }
    if (Game.keys[' ']) {
        shootBullet();
    }
    // 添加按q键替换图片的逻辑
    if (Game.keys['q']) {
        replacePlayerImage('./js/bs.jpg');
    }
    // 添加松开q键恢复原来图片的逻辑
    if (!Game.keys['q']) {
        replacePlayerImage(originalImageSrc);
    }
}

export function drawPlayer(ctx) {
    // 玩家绘制逻辑
    ctx.save();
    ctx.translate(canvas.width / 2, canvas.height / 2);  // 现在使用导入的 canvas
    ctx.rotate(Game.player.direction * Math.PI / 2);
    // 确保 Game.player.image 是一个有效的 HTMLImageElement
    if (Game.player.image && Game.player.image.complete) {
        ctx.drawImage(Game.player.image, -Game.player.width / 2, -Game.player.height / 2, Game.player.width, Game.player.height);
    } else {
        // 如果图像尚未加载完成，可以绘制一个占位矩形或其他内容
        ctx.fillStyle = 'red';
        ctx.fillRect(-Game.player.width / 2, -Game.player.height / 2, Game.player.width, Game.player.height);
    }
    ctx.restore();

}
